<template>
  <div id="ctreatFirstCampus">
    <div
      class="dialog animated"
      :class="open? 'fadeIn':'fadeOut'"
      v-show="show"
      :style="{visibility: (open?'visible':'hidden')}"
    >
      <div class="panel animated" :class="open? 'zoomIn':''">
        <div class="title">
          {{title}}
          <div class="close" @click="cancel()"></div>
        </div>
        <div>
          <el-form :model="campusData" ref="campusData" label-width="240px">
            <el-form-item label="校区名称" :rules="[
      { required: true, message: ''}]">
              <el-input
                style="width:50%"
                clearable
                v-model="campusData.name"
                :disabled="isEnable"
                placeholder="请输入校区名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属机构" v-if="orgList.length>0">
              <el-select
                style="width:50%"
                v-model="campusData.orgId"
                :disabled="isShow"
                clearable
                placeholder="请选择机构"
              >
                <el-option
                  v-for="item in orgList"
                  :key="item.orgId"
                  :label="item.orgName"
                  :value="item.orgId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="校区电话">
              <el-input
                style="width:50%"
                :disabled="isShow"
                clearable
                maxlength="12"
                v-model="campusData.tel"
                placeholder="请输入校区电话、如：020-12345678"
              ></el-input>
            </el-form-item>
            <el-form-item label="校区logo">
              <el-upload
                class="avatar-uploader"
                style="margin-top:0.36rem;"
                :action="uploadUrl"
                :show-file-list="false"
                :disabled="isShow"
                :data="uploadData"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                :on-error="uploadError"
                accept=".jpg, .png"
              >
                <img @click="clickPic(false)" v-if="imgUrl_44" :src="imgUrl_44" class="avatar" />
                <img
                  @click="clickPic(false)"
                  :disabled="isShow"
                  src="../../assets/img/system_set/def_logo1.jpg"
                  v-else
                />
                <div
                  slot="tip"
                  class="el-upload__tip"
                  style="line-height: 0.3rem;margin-top:-0.1rem;font-size:0.14rem;"
                >210x82</div>
              </el-upload>
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :disabled="isShow"
                :data="uploadData"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                :on-error="uploadError"
                accept=".jpg, .png"
              >
                <img @click="clickPic(true)" v-if="imgUrl_202" :src="imgUrl_202" class="avatar" />
                <img
                  @click="clickPic(true)"
                  :disabled="isShow"
                  src="../../assets/img/system_set/def_logo2.jpg"
                  v-else
                />
                <div
                  slot="tip"
                  class="el-upload__tip"
                  style="line-height: 0.3rem;margin-top:-0.1rem;font-size:0.14rem;padding-left:0.7rem"
                >202x44</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="校区所在地区" :rules="[
      { required: true, message: ''}]">
              <el-cascader
                style="width:50%"
                clearable
                :disabled="isShow"
                :props="defaultProps"
                :options="citys"
                v-model="campusData.regionAddress"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="校区详细地址">
              <el-input
                style="width:50%"
                clearable
                :disabled="isShow"
                v-model="campusData.address"
                placeholder="请输入校区详细地址"
              ></el-input>
            </el-form-item>
            <el-form-item label="校长姓名" :rules="[
      { required: true, message: ''}]">
              <el-input
                style="width:50%"
                clearable
                :disabled="isShow"
                v-model="campusData.contactsName"
                placeholder="请输入校长姓名"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" :rules="[
      { required: true, message: ''}]">
              <el-input
                style="width:50%"
                clearable
                :disabled="isShow"
                v-model="campusData.contactsTel"
                type="text"
                maxlength="11"
                oninput="value=value.replace(/[^\d]/g,'')"
                onpaste="return false;"
                placeholder="请输入校长手机号，并为该校区管理员账号"
              ></el-input>
            </el-form-item>
            <el-form-item label="合作类型" :rules="[
      { required: true, message: ''}]">
              <el-select
                style="width:50%"
                :disabled="isShow"
                @change="orgModeChange"
                v-model="campusData.cooperationMode"
                clearable
                placeholder="请选择合作类型"
              >
                <el-option
                  v-for="item in cooperationModeList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="服务期限"
              v-if="campusData.cooperationMode != 2"
              :rules="[
      { required: true, message: ''}]"
            >
              <el-row style="width:50%">
                <el-col :span="10">
                  <el-date-picker
                    type="date"
                    :disabled="isShow"
                    placeholder="开始日期"
                    v-model="campusData.serveStartTime"
                    style="width: 100%;"
                  ></el-date-picker>
                </el-col>
                <el-col style="text-align: center;" :span="3">-</el-col>
                <el-col :span="11">
                  <el-date-picker
                    type="date"
                    :disabled="isShow"
                    placeholder="结束日期"
                    v-model="campusData.serveEndTime"
                    style="width: 100%;"
                  ></el-date-picker>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="校区公众号ID">
            <el-input
              style="width:50%"
              clearable
              :disabled="isShow"
              maxlength="50"
              v-model="campusData.appId"
              placeholder="请输入校区公众号ID"
            ></el-input>
          </el-form-item>
            <el-form-item label="备注">
              <el-input
                style="width:50%"
                clearable
                :disabled="isShow"
                v-model="campusData.remark"
                placeholder="请输入补充说明信息"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="btn_div" v-if="!isShow">
          <div class="btn_sure" @click="sure()">确 认</div>
          <div class="btn_cancel" @click="cancel()">取 消</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import citys from "@/../static/citys.json";
var vm;
export default {
  data: function() {
    return {
      show: false,
      open: false,
      isAdd: true,
      isShow: false,
      isEnable: false,
      title: "",
      citys: [],
      orgList: [],
      isTwo: false,
      imgUrl_44: "",
      imgUrl_202: "",
      uploadData: {
        content: "campuslogo"
      },
      campusData: {},
      cooperationModeList: [],
      uploadUrl: window.config.baseUrl + "/file/upload",
      orgModeList: [],
      defaultProps: {
        label: "label",
        value: "value",
        children: "children"
      },
      headers: {
        // 'Content-Type': 'multipart/form-data',
        token: tool.getItem(lsKey.token)
      }
    };
  },
  methods: {
    clickPic(isTwo) {
      vm.isTwo = isTwo;
    },
    orgModeChange: function(val) {
      if (val == 2) {
        vm.campusData.serveStartTime = "1946-02-14";
        vm.campusData.serveEndTime = "2999-12-30";
      } else {
        vm.campusData.serveStartTime = "";
        vm.campusData.serveEndTime = "";
      }
    },
    uploadError: function(response, file) {
      console.log("上传文件失败response" + response);
    },
    handleAvatarSuccess(res, file) {
      if (res.status != "success") {
        this.$message.error("上传文件失败，错误码" + res.errorCode);
      } else {
        if (!vm.isTwo) {
          this.imgUrl_44 = res.data.url;
        } else {
          this.imgUrl_202 = res.data.url;
        }
        // this.campusData.icon = res.data.url;
      }
    },
    beforeAvatarUpload(file) {
      console.log(file);
      const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传logo图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传logo图片大小不能超过 2MB!");
        return false;
      }
      let fontSize;
      if (!vm.isTwo) {
        fontSize = "44x44";
      } else {
        fontSize = "210x82";
      }

      const isSize = new Promise(function(resolve, reject) {
        let width = fontSize.split("x")[0];
        let height = fontSize.split("x")[1];
        let _URL = window.URL || window.webkitURL;
        let image = new Image();
        image.onload = function() {
          let value = image.width == width && image.height == height;
          value ? resolve() : reject();
        };
        image.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          tool.message({
            showClose: true,
            message: "上传logo图片尺寸不符合，应为" + fontSize,
            type: "warning"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    init: function(data) {
      vm.show = true;
      setTimeout(function() {
        vm.open = true;
      }, 11);
      let user = tool.getItem(lsKey.user, true); //得到当前用户信息
      console.log(tool.getItem(lsKey.token));
      vm.headers.token = tool.getItem(lsKey.token);
      console.log(vm.headers.token);
      //获取数据字典
      let dicdata = tool.getItem(lsKey.dict, true);
      vm.cooperationModeList = dicdata["cooperation_mode"];
      vm.citys = citys;
      vm.isAdd = true;
      vm.title = "新增校区";
      vm.campusData = {
        orgId: "",
        name: "",
        tel: "",
        icon: "",
        regionAddress: [],
        province: "",
        city: "",
        area: "",
        address: "",
        contactsName: "",
        contactsTel: "",
        cooperationMode: "",
        serveStartTime: "",
        serveEndTime: "",
        remark: "",
          appId: ""
      };
      vm.campusData.orgId = user.orgId;
    },
    cancel: function() {
      //隐藏弹窗
      vm.open = false;
      vm.isAdd = true;
      vm.isShow = false;
      vm.isEnable = false;
      vm.imgUrl = "";
      setTimeout(function() {
        vm.show = false;
        vm.$emit("cancel", "关闭");
      }, 500);
    },
    sure: function() {
      console.log(vm.campusData.regionAddress);
      if (vm.campusData.name == "") {
        this.$message.warning("校区名称不能为空");
        return;
      }
      if (vm.campusData.name.indexOf(" ") != -1) {
        this.$message.warning("校区名称不能有空字符");
        return;
      }
      if (vm.campusData.orgId == "") {
        this.$message.warning("所属机构不能为空");
        return;
      }
      if (
        (vm.imgUrl_44 == "" && vm.imgUrl_202 != "") ||
        (vm.imgUrl_44 != "" && vm.imgUrl_202 == "")
      ) {
        this.$message.warning("如需上传校区logo，则必须上传两种分辨率的logo");
        return;
      }
      if (vm.campusData.contactsName == "") {
        this.$message.warning("校长负责人不能为空");
        return;
      }
      if (vm.campusData.contactsTel == "") {
        this.$message.warning("校长手机不能为空");
        return;
      }
      if (!tool.judge("phone", vm.campusData.contactsTel)) {
        this.$message.warning("手机号不匹配!");
        return;
      }
      if (vm.campusData.cooperationMode == "") {
        this.$message.warning("合作模式不能为空");
        return;
      }
      if (vm.campusData.serveStartTime == "") {
        this.$message.warning("服务开始时间不能为空");
        return;
      }
      if (vm.campusData.serveEndTime == "") {
        this.$message.warning("服务结束时间不能为空");
        return;
      }
      if (vm.campusData.regionAddress.length > 0) {
        vm.campusData.province = vm.campusData.regionAddress[0];
        vm.campusData.city = vm.campusData.regionAddress[1];
        vm.campusData.area = vm.campusData.regionAddress[2];
      } else {
        this.$message.warning("请选择校区所在的省市区");
        return;
      }
      if (vm.campusData.serveStartTime instanceof Date) {
        vm.campusData.serveStartTime = tool.DateToString(
          vm.campusData.serveStartTime,
          "yyyy-MM-dd"
        );
      }
      if (vm.campusData.serveEndTime instanceof Date) {
        vm.campusData.serveEndTime = tool.DateToString(
          vm.campusData.serveEndTime,
          "yyyy-MM-dd"
        );
      }
      if (vm.imgUrl_44 != "") {
        vm.campusData.icon = vm.imgUrl_44 + "," + vm.imgUrl_202;
      }
      if (vm.isAdd) {
        api.campusAdd(vm.campusData).then(function(data) {
          console.log(data);
          if (data.result == "操作成功") {
            vm.$message({
              message: "添加成功",
              type: "success"
            });
            vm.$emit("callback", "添加成功");
            //隐藏弹窗
            vm.open = false;
            vm.isAdd = true;
            vm.isShow = false;
            vm.isEnable = false;
            vm.imgUrl = "";
            setTimeout(function() {
              vm.show = false;
            }, 500);
          } else {
            vm.$message.error(data.result);
          }
        });
      } else {
        // paras.userId = vm.accountData.userId;
        api.campusUpdate(vm.campusData).then(function(data) {
          console.log(data);
          if (data.result == "操作成功") {
            vm.$message({
              message: "修改成功",
              type: "success"
            });
            vm.$emit("callback", "修改成功");
            //隐藏弹窗
            vm.open = false;
            vm.isAdd = true;
            vm.isShow = false;
            vm.isEnable = false;
            vm.imgUrl = "";
            setTimeout(function() {
              vm.show = false;
            }, 500);
          } else {
            vm.$message.error(data.result);
          }
        });
      }
    }
  },
  created: function() {
    vm = this;
  }
};
</script>
<style lang="scss">
#ctreatFirstCampus {
  text-align: start;
}
</style>
<style scoped>
.dialog {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  overflow-y: auto;
  animation-duration: 0.5s !important;
  /*z-index: 3000;*/
  z-index: 30;
}
.dialog::-webkit-scrollbar {
  width: 0;
}
/* 内容面板 */
.panel {
  width: 10rem;
  margin: 0.6rem auto 0.3rem auto;
  background-color: white;
  border-radius: 0.1rem;
  animation-duration: 0.5s !important;
  letter-spacing: 0.01rem;
}
/* 顶部标题和关闭按钮 */
.title {
  font-size: 0.22rem;
  color: #333333;
  padding: 0.23rem 0.27rem 0.15rem 0.3rem;
}
.close {
  float: right;
  width: 0.25rem;
  height: 0.25rem;
  background-image: url(../../assets/img/clue_manage/close.png);
  background-size: 0.16rem;
  background-repeat: no-repeat;
  background-position: center center;
  cursor: pointer;
}

/*底部按钮*/
.btn_div {
  width: 3.5rem;
  margin: 0 auto;
  padding: 0.3rem 0;
  overflow: hidden;
}
.btn_div > div {
  width: 1.6rem;
  height: 0.4rem;
  line-height: 0.4rem;
  float: left;
  font-size: 0.16rem;
  text-align: center;
  border-radius: 0.05rem;
  cursor: pointer;
  user-select: none;
}

.btn_disable {
  color: #999999;
  background-color: #dedede;
  margin-right: 0.3rem;
  cursor: not-allowed !important;
}
.btn_sure {
  color: white;
  background-color: #3885f8;
  margin-right: 0.3rem;
}
.btn_sure:hover {
  background-color: rgba(56, 133, 248, 0.8);
}
.btn_cancel {
  color: #666666;
  border: 0.01rem solid #c0c4cc;
}
.btn_cancel:hover {
  background-color: rgba(56, 133, 248, 0.1);
}
.ruleForm {
  padding-left: 0.5rem;
}
.el-radio-group {
  line-height: inherit;
}

.el-col {
  border-radius: 4px;
}
.bg-purple {
  background: #d3dce6;
}
.grid-content {
  line-height: 0.5rem;
  text-align: center;
}
.avatar-uploader {
  float: left;
  margin-left: 0.2rem;
}
.avatar-uploader .el-upload {
  border: 1px dashed #453374;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}
.avatar {
  display: block;
  object-fit: cover;
}
</style>
